﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Saxon.Api;
using WSManager.Model;

namespace WSManager.Logic.Transformation.Articles
{
    public class XmlArticleTransformer: ArticleTransformer
    {
        XsltTransformer xslt;

        public XmlArticleTransformer(string xsltFileName)
        {
            xslt = XsltTransformerFactory.LoadXslt(xsltFileName);
        }

        public override XElement ConvertStream(System.IO.Stream stream)
        {
            var xml = XDocument.Load(stream).Root;
            return ConvertXml(xml);
        }

        public XElement ConvertXml(XElement xml)
        {
            var ser = new Serializer();
            var stream = new MemoryStream();
            ser.SetOutputStream(stream);
            xslt.InitialContextNode = XsltTransformerFactory.BuildDocument(xml.CreateReader());
            xslt.Run(ser);
            stream.Position = 0;
            return XElement.Load(stream);
        }
    }
}
